package com.ruoyi.web.controller.datasync;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.datasync.SyncServer;
import com.ruoyi.system.service.ISyncServerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.util.StringUtils;

/**
 * 服务器Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/sync/server")
public class SyncServerController extends BaseController
{
    @Autowired
    private ISyncServerService syncServerService;

    /**
     * 查询服务器列表
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:list')")
    @GetMapping("/list")
    public TableDataInfo list(SyncServer syncServer)
    {
        startPage();
        List<SyncServer> list = syncServerService.selectSyncServerList(syncServer);
        return getDataTable(list);
    }

    /**
     * 导出服务器列表
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:export')")
    @Log(title = "服务器", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SyncServer syncServer)
    {
        List<SyncServer> list = syncServerService.selectSyncServerList(syncServer);
        ExcelUtil<SyncServer> util = new ExcelUtil<SyncServer>(SyncServer.class);
        util.exportExcel(response, list, "服务器数据");
    }

    /**
     * 获取服务器详细信息
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:query')")
    @GetMapping(value = "/{serverId}")
    public AjaxResult getInfo(@PathVariable("serverId") Long serverId)
    {
        return success(syncServerService.selectSyncServerByServerId(serverId));
    }

    /**
     * 新增服务器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:add')")
    @Log(title = "服务器", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SyncServer syncServer)
    {
        return toAjax(syncServerService.insertSyncServer(syncServer));
    }

    /**
     * 修改服务器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:edit')")
    @Log(title = "服务器", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SyncServer syncServer)
    {
        return toAjax(syncServerService.updateSyncServer(syncServer));
    }

    /**
     * 删除服务器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:remove')")
    @Log(title = "服务器", businessType = BusinessType.DELETE)
    @DeleteMapping("/{serverIds}")
    public AjaxResult remove(@PathVariable Long[] serverIds)
    {
        return toAjax(syncServerService.deleteSyncServerByServerIds(serverIds));
    }

    /**
     * 测试服务器连接
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:test')")
    @Log(title = "服务器", businessType = BusinessType.OTHER)
    @GetMapping("/test/{serverId}")
    public AjaxResult testConnection(@PathVariable("serverId") Long serverId)
    {
        boolean result = syncServerService.testServerConnection(serverId);
        if (result) {
            return success("连接成功");
        } else {
            return error("连接失败");
        }
    }

    /**
     * 获取服务器选项列表
     */
    @GetMapping("/options")
    public AjaxResult getServerOptions()
    {
        List<SyncServer> servers = syncServerService.selectServerOptions();
        return success(servers);
    }

    /**
     * 获取服务器下的文件目录
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:query')")
    @GetMapping("/files/{serverId}")
    public AjaxResult listServerFiles(@PathVariable("serverId") Long serverId, String dirPath)
    {
        List<Map<String, Object>> files = syncServerService.listServerFiles(serverId, dirPath);
        return AjaxResult.success(files);
    }

    /**
     * 执行服务器命令
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @Log(title = "服务器命令", businessType = BusinessType.OTHER)
    @PostMapping("/command/{serverId}")
    public AjaxResult executeCommand(@PathVariable("serverId") Long serverId, @RequestBody Map<String, String> params)
    {
        String command = params.get("command");
        if (StringUtils.isEmpty(command)) {
            return AjaxResult.error("命令不能为空");
        }
        
        Map<String, Object> result = syncServerService.executeCommand(serverId, command);
        return AjaxResult.success(result);
    }

    /**
     * 获取服务器进程列表
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @GetMapping("/processes/{serverId}")
    public AjaxResult getServerProcesses(@PathVariable("serverId") Long serverId)
    {
        List<Map<String, Object>> processes = syncServerService.getServerProcesses(serverId);
        return AjaxResult.success(processes);
    }

    /**
     * 终止服务器进程
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/process/kill/{serverId}")
    public AjaxResult killServerProcess(@PathVariable("serverId") Long serverId, @RequestBody Map<String, String> params)
    {
        String pid = params.get("pid");
        if (StringUtils.isEmpty(pid)) {
            return AjaxResult.error("进程ID不能为空");
        }
        
        boolean result = syncServerService.killServerProcess(serverId, pid);
        return result ? AjaxResult.success() : AjaxResult.error("终止进程失败");
    }

    /**
     * 获取Docker信息
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @GetMapping("/docker/info/{serverId}")
    public AjaxResult getDockerInfo(@PathVariable("serverId") Long serverId)
    {
        return success(syncServerService.getDockerInfo(serverId));
    }

    /**
     * 获取Docker容器列表
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @GetMapping("/docker/containers/{serverId}")
    public AjaxResult getDockerContainers(@PathVariable("serverId") Long serverId)
    {
        return success(syncServerService.getDockerContainers(serverId));
    }

    /**
     * 获取Docker镜像列表
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @GetMapping("/docker/images/{serverId}")
    public AjaxResult getDockerImages(@PathVariable("serverId") Long serverId)
    {
        return success(syncServerService.getDockerImages(serverId));
    }

    /**
     * 获取Docker Compose文件列表
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @GetMapping("/docker/compose/files/{serverId}")
    public AjaxResult getDockerComposeFiles(@PathVariable("serverId") Long serverId, @RequestParam String dirPath)
    {
        return success(syncServerService.getDockerComposeFiles(serverId, dirPath));
    }

    /**
     * 读取Docker Compose文件内容
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @GetMapping("/docker/compose/read/{serverId}")
    public AjaxResult readDockerComposeFile(@PathVariable("serverId") Long serverId, @RequestParam String filePath)
    {
        return success(syncServerService.readDockerComposeFile(serverId, filePath));
    }

    /**
     * 迁移Docker容器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/migrate/container")
    public AjaxResult migrateDockerContainer(@RequestBody Map<String, Object> params)
    {
        Long sourceServerId = Long.parseLong(params.get("sourceServerId").toString());
        Long targetServerId = Long.parseLong(params.get("targetServerId").toString());
        String containerId = (String) params.get("containerId");
        
        return success(syncServerService.migrateDockerContainer(sourceServerId, targetServerId, containerId));
    }

    /**
     * 迁移Docker Compose配置
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/migrate/compose")
    public AjaxResult migrateDockerCompose(@RequestBody Map<String, Object> params)
    {
        Long sourceServerId = Long.parseLong(params.get("sourceServerId").toString());
        Long targetServerId = Long.parseLong(params.get("targetServerId").toString());
        String composePath = (String) params.get("composePath");
        
        return success(syncServerService.migrateDockerCompose(sourceServerId, targetServerId, composePath));
    }

    /**
     * 一键迁移所有Docker容器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/migrate/all-containers")
    public AjaxResult migrateAllDockerContainers(@RequestBody Map<String, Object> params)
    {
        Long sourceServerId = Long.parseLong(params.get("sourceServerId").toString());
        Long targetServerId = Long.parseLong(params.get("targetServerId").toString());
        
        return success(syncServerService.migrateAllDockerContainers(sourceServerId, targetServerId));
    }
    
    /**
     * 迁移Docker镜像
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/migrate/image")
    public AjaxResult migrateDockerImage(@RequestBody Map<String, Object> params)
    {
        Long sourceServerId = Long.parseLong(params.get("sourceServerId").toString());
        Long targetServerId = Long.parseLong(params.get("targetServerId").toString());
        String imageId = (String) params.get("imageId");
        
        return success(syncServerService.migrateDockerImage(sourceServerId, targetServerId, imageId));
    }

    /**
     * 获取可用软件包列表
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @GetMapping("/software/available/{serverId}")
    public AjaxResult getAvailableSoftwarePackages(@PathVariable("serverId") Long serverId, String keyword)
    {
        return success(syncServerService.getAvailableSoftwarePackages(serverId, keyword));
    }
    
    /**
     * 获取已安装软件包列表
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @GetMapping("/software/installed/{serverId}")
    public AjaxResult getInstalledSoftwarePackages(@PathVariable("serverId") Long serverId, String keyword)
    {
        return success(syncServerService.getInstalledSoftwarePackages(serverId, keyword));
    }
    
    /**
     * 安装软件包
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/software/install/{serverId}")
    public AjaxResult installSoftwarePackage(@PathVariable("serverId") Long serverId, @RequestBody Map<String, String> params)
    {
        String packageName = params.get("packageName");
        if (StringUtils.isEmpty(packageName)) {
            return AjaxResult.error("软件包名称不能为空");
        }
        
        return success(syncServerService.installSoftwarePackage(serverId, packageName));
    }
    
    /**
     * 卸载软件包
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/software/uninstall/{serverId}")
    public AjaxResult uninstallSoftwarePackage(@PathVariable("serverId") Long serverId, @RequestBody Map<String, String> params)
    {
        String packageName = params.get("packageName");
        if (StringUtils.isEmpty(packageName)) {
            return AjaxResult.error("软件包名称不能为空");
        }
        
        return success(syncServerService.uninstallSoftwarePackage(serverId, packageName));
    }
    
    /**
     * 更新软件包
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/software/update/{serverId}")
    public AjaxResult updateSoftwarePackage(@PathVariable("serverId") Long serverId, @RequestBody Map<String, String> params)
    {
        String packageName = params.get("packageName");
        return success(syncServerService.updateSoftwarePackage(serverId, packageName));
    }

    /**
     * 设置服务器之间的SSH免密登录
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @Log(title = "SSH免密登录设置", businessType = BusinessType.OTHER)
    @PostMapping("/ssh/setup-keyauth")
    public AjaxResult setupSSHKeyAuth(@RequestBody Map<String, Object> params)
    {
        Long sourceServerId = Long.parseLong(params.get("sourceServerId").toString());
        Long targetServerId = Long.parseLong(params.get("targetServerId").toString());
        
        return success(syncServerService.setupSSHKeyAuth(sourceServerId, targetServerId));
    }

    /**
     * 启动Docker容器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/container/start/{serverId}")
    public AjaxResult startDockerContainer(@PathVariable("serverId") Long serverId, @RequestBody Map<String, String> params)
    {
        String containerId = params.get("containerId");
        if (StringUtils.isEmpty(containerId)) {
            return AjaxResult.error("容器ID不能为空");
        }
        
        return success(syncServerService.startDockerContainer(serverId, containerId));
    }
    
    /**
     * 停止Docker容器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/container/stop/{serverId}")
    public AjaxResult stopDockerContainer(@PathVariable("serverId") Long serverId, @RequestBody Map<String, String> params)
    {
        String containerId = params.get("containerId");
        if (StringUtils.isEmpty(containerId)) {
            return AjaxResult.error("容器ID不能为空");
        }
        
        return success(syncServerService.stopDockerContainer(serverId, containerId));
    }
    
    /**
     * 删除Docker容器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/container/remove/{serverId}")
    public AjaxResult removeDockerContainer(@PathVariable("serverId") Long serverId, @RequestBody Map<String, String> params)
    {
        String containerId = params.get("containerId");
        if (StringUtils.isEmpty(containerId)) {
            return AjaxResult.error("容器ID不能为空");
        }
        
        return success(syncServerService.removeDockerContainer(serverId, containerId));
    }
    
    /**
     * 获取Docker容器日志
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @GetMapping("/docker/container/logs/{serverId}")
    public AjaxResult getDockerContainerLogs(@PathVariable("serverId") Long serverId, 
                                           @RequestParam String containerId,
                                           @RequestParam(required = false) Integer lines)
    {
        if (StringUtils.isEmpty(containerId)) {
            return AjaxResult.error("容器ID不能为空");
        }
        
        return success(syncServerService.getDockerContainerLogs(serverId, containerId, lines));
    }
    
    /**
     * 安装Docker Compose
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/compose/install/{serverId}")
    public AjaxResult installDockerCompose(@PathVariable("serverId") Long serverId, @RequestBody(required = false) Map<String, String> params)
    {
        String version = null;
        String installMethod = "user"; // 默认为当前用户安装
        if (params != null) {
            version = params.get("version");
            if (params.containsKey("installMethod")) {
                installMethod = params.get("installMethod");
            }
        }
        return success(syncServerService.installDockerCompose(serverId, version, installMethod));
    }

    /**
     * 使用Docker Compose部署容器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/compose/run/{serverId}")
    public AjaxResult runDockerCompose(@PathVariable("serverId") Long serverId, @RequestBody Map<String, String> params)
    {
        String composeFilePath = params.get("composeFilePath");
        String operation = params.get("operation");
        
        if (StringUtils.isEmpty(composeFilePath)) {
            return error("Compose文件路径不能为空");
        }
        
        return success(syncServerService.runDockerCompose(serverId, composeFilePath, operation));
    }

    /**
     * 将容器导出为Docker Compose配置
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @PostMapping("/docker/compose/generate")
    public AjaxResult generateDockerCompose(@RequestBody Map<String, Object> params)
    {
        Long serverId = Long.parseLong(params.get("serverId").toString());
        String containerId = (String) params.get("containerId");
        String outputPath = (String) params.get("outputPath");
        Boolean allContainers = params.get("allContainers") != null ? 
                              Boolean.parseBoolean(params.get("allContainers").toString()) : false;
        
        return success(syncServerService.generateDockerCompose(serverId, containerId, outputPath, allContainers));
    }

    /**
     * 将文件从一个服务器同步到另一个服务器
     */
    @PreAuthorize("@ss.hasPermi('datasync:server:manage')")
    @Log(title = "服务器文件同步", businessType = BusinessType.OTHER)
    @PostMapping("/file/sync")
    public AjaxResult syncFileBetweenServers(@RequestBody Map<String, Object> params)
    {
        if (params.get("sourceServerId") == null || params.get("targetServerId") == null) {
            return AjaxResult.error("源服务器ID和目标服务器ID不能为空");
        }
        
        if (params.get("sourcePath") == null || params.get("targetPath") == null) {
            return AjaxResult.error("源文件路径和目标文件路径不能为空");
        }
        
        Long sourceServerId = Long.valueOf(params.get("sourceServerId").toString());
        Long targetServerId = Long.valueOf(params.get("targetServerId").toString());
        String sourcePath = params.get("sourcePath").toString();
        String targetPath = params.get("targetPath").toString();
        
        Map<String, Object> result = syncServerService.syncFileBetweenServers(sourceServerId, targetServerId, sourcePath, targetPath);
        return AjaxResult.success(result);
    }
} 